<template>
  <div id="main">
      <div class="select-option">
        <a-space size="middle">
          <span><a-icon type="caret-right" />{{ currentProvider.title }}</span>
          <a class="menu-option" @click="showDrawer"><a-icon type="retweet" />&nbsp;切换服务</a>
          <a class="menu-option">
            <a-popconfirm
              cancelText="取消"
              okText="确定"
              title="确定备份么？"
              @confirm="handleBackup()">
              <a-icon slot="icon" type="question-circle-o" style="color: green" />
              <a-icon type="cloud-download" />&nbsp;数据备份
            </a-popconfirm>
          </a>
          <a-upload
            name="file"
            :multiple="false"
            :action="importUrl"
            @change="handleImport"
            :showUploadList="false"
            :beforeUpload="checkImportFile"
          >
            <a class="menu-option">
              <a-icon type="cloud-upload" /> 数据导入
              <a-spin :spinning="importLoading" />
            </a>
          </a-upload>
        </a-space>
      </div>
      <div class="file-upload">
        <a-upload-dragger
            name="file"
            :data="uploadParams"
            :multiple="false"
            :action="actionUrl"
            @change="handleUploadChange"
            :showUploadList="isShowUploadList"
            :beforeUpload="checkBeforeFile"
        >
            <p class="ant-upload-drag-icon">
            <a-icon type="inbox" />
            </p>
            <p class="ant-upload-text">
              点击 或 拖拽上传
            </p>
        </a-upload-dragger>
        <p/>
      </div>
      <div class="upload-result">
        <a-list v-if="uploadFiles.length !== 0" size="small" :dataSource="uploadFiles" :split="false">
          <a-list-item slot="renderItem" slot-scope="item, index">
            <a-card class="file-format" size="small" :title="((index+1) + '. ' + item.originalName)">
              <p :key="fIndex" v-for="(formatInfo, fIndex) in item.formatUrls">
                <a-input-group compact>
                  <a-input class="f-title" :default-value="formatInfo.title" />
                  <a-input-search class="f-content" :default-value="formatInfo.content" @search="handleCopy">
                    <a-button class="copy-code-button" slot="enterButton" :data-clipboard-text="formatInfo.content">
                      复制
                    </a-button>
                  </a-input-search>
                </a-input-group>
              </p>
            </a-card>
          </a-list-item>
        </a-list>
      </div>
      <div>
        <a-drawer
          title="选择服务"
          placement="right"
          :closable="false"
          :visible="drawerVisible"
          @close="onClose"
        >
          <a-radio-group v-model="cPid" @change="handleChangeProvider">
            <a-radio :style="radioStyle" :value="pItem.pid" :key="pIndex" v-for="(pItem, pIndex) in providers">
              {{ pItem.title }}
            </a-radio>
          </a-radio-group>
        </a-drawer>
      </div>
  </div>
</template>
<script>
import storage from 'store'
import { PROVIDER } from '@/store/mutation-types'
import COMMON from '@/store/common'
import _ from 'lodash'
import path from 'path'
import Clipboard from 'clipboard'
import { localApi } from '@/api/main'

export default {
  data() {
    return {
      actionUrl: process.env.VUE_APP_API_BASE_URL + '/api/v1/pic/uploadFile',
      importUrl: process.env.VUE_APP_API_BASE_URL + '/api/v1/pic/importData',
      uploadFiles: [],
      uploadParams: {},
      providers: COMMON.providers,
      currentProvider: COMMON.providers[0],
      cPid: COMMON.smms,
      drawerVisible: false,
      radioStyle: {
        display: 'block',
        height: '30px',
        lineHeight: '30px',
      },
      isShowUploadList: true,
      importLoading: false,
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init () {
      const provider = storage.get(PROVIDER)
      if (!_.isEmpty(provider)) {
        this.currentProvider = provider;
      }
      this.cPid = this.currentProvider.pid;
      this.uploadParams.pid = this.cPid;
      storage.set(PROVIDER, this.currentProvider);
    },
    showDrawer() {
      this.drawerVisible = true;
    },
    onClose() {
      this.drawerVisible = false;
    },
    handleChangeProvider(e) {
      this.cPid = e.target.value;
      //console.log('pid:', pid);
      this.currentProvider = _.find(this.providers, ['pid', this.cPid]);
      //console.log('providerData:', this.currentProvider);
      this.uploadParams.pid = this.cPid;
      storage.set(PROVIDER, this.currentProvider);
    },
    checkFileSmms (file, fileLimit, checkRes) {
      if (file.size > fileLimit.maxSize) {
        checkRes = {
          success: false,
          notice: {
            message: 'SM.MS限制',
            description: `图片太大，超过了5M限制`,
            duration: 4.5
          }
        }
      }
      const extname = path.extname(file.name);
      if (!_.includes(fileLimit.types, extname)) {
        checkRes = {
          success: false,
          notice: {
            message: 'SM.MS限制',
            description: `仅支持jpeg, jpg, png, gif, bmp文件类型`,
            duration: 4.5
          }
        }
      }
      return checkRes;
    },
    checkBeforeFile (file) {
      const fileLimit = this.currentProvider.limit;
      let checkRes = {
        success: true,
        notice: {}
      };
      switch (this.cPid) {
        case COMMON.smms :
          checkRes = this.checkFileSmms(file, fileLimit, checkRes);
          break;
        case COMMON.github :
          
          break;
        case COMMON.aliyunoss :
        
          break;    
        case COMMON.txcos :
        
          break;    
        case COMMON.qiniu :
        
          break;
        case COMMON.upyun :

          break;
      }
      return new Promise ((resolve, reject) => {
        if (checkRes.success !== true) {
          this.$notification.error(checkRes.notice);
          return reject(false)
        }
        return resolve(true);
      });
    },
    handleUploadChange (info) {
      this.uploadFiles = [];
      const status = info.file.status;
      if (status !== 'uploading') {
        //console.log(info.file);
      }
      if (status === 'done') {
        const uploadRes = info.file.response;
        //console.log('uploadRes:', uploadRes);
        if (uploadRes.code !== 0) {
          this.$notification.error({
            message: '上传失败',
            description: `${uploadRes.msg}`,
            duration: 6
          });
          return false;
        }
        let fileInfo = uploadRes.data;
        this.uploadFiles.unshift(fileInfo);
        //this.$set(this.uploadFiles, this.uploadFiles.length, fileInfo);
        this.$notification.success({
          message: '上传成功',
          description: ``,
          duration: 2
        });
      } else if (status === 'error') {
        this.$notification.error({
          message: '上传失败',
          description: '异常错误',
          duration: 4.5
        });
      }
    },
    handleCopy () {
      const clipboard = new Clipboard('.copy-code-button')
      clipboard.on('success', e => {
          this.$notification.success({
            message: '复制成功',
            description: '',
            duration: 1
          });
          // 释放内存
          clipboard.destroy()
      })
    },
    handleBackup () {
      localApi('exportData', {}).then(res => {
        if (res.code !== 0) {
          this.$notification.warning({
            message: res.msg,
            description: '',
            duration: 2
          });
          return false;
        }
        this.$notification.success({
          message: res.msg,
          description: '',
          duration: 2
        });
      }).catch(err => {
        console.log('err:', err)
      })
    },
    handleImport (info) {
      this.importLoading = true;
      const status = info.file.status;
      if (status !== 'uploading') {
        //console.log(info.file);
      }
      if (status === 'done') {
        this.importLoading = false;
        const uploadRes = info.file.response;
        //console.log('uploadRes:', uploadRes);
        if (uploadRes.code !== 0) {
          this.$notification.error({
            message: '导入失败',
            description: `${uploadRes.msg}`,
            duration: 6
          });
          return false;
        }
        
        this.$notification.success({
          message: '',
          description: `导入成功`,
          duration: 2
        });
      } else if (status === 'error') {
        this.$notification.error({
          message: '上传失败',
          description: '异常错误',
          duration: 4.5
        });
      }
    }, 
    checkImportFile (file) {
      //console.log('file:', file);
      let checkRes = {
        success: true,
        notice: {}
      };
      if (file.type !== 'application/json') {
        checkRes = {
          success: false,
          notice: {
            message: '文件错误',
            description: `请检查上传文件`,
            duration: 4.5
          }
        }
      }
      return new Promise ((resolve, reject) => {
        if (checkRes.success !== true) {
          this.$notification.error(checkRes.notice);
          return reject(false)
        }
        return resolve(true);
      });
    },    
  },
};
</script>
<style lang="less" scoped>
#main {
  .select-option {
    border-top: 1px dashed #e8e8e8;
    border-bottom: 1px dashed #e8e8e8;
    color: #000;
    padding: 9px 10px;
    text-align: left;
    .menu-option {
      color: #000;
    }
    a:hover{ 
      color:#1890ff;
    }
  }
  .file-upload {
    padding: 10px;
  }
  .upload-result {
    padding: 10px;
    .file-format {
      width: 100%;
      color: #000;
      text-align: left;
      .f-title {
        width: 15%;
        background-color: #FAFAFA;
      }
      .f-content {
        width: 85%;
      }
      .copy-code-button {
        background-color: #FAFAFA;
      }
    }
  }
}
</style>
